package com.bdqn.t350.dao.impl;

import com.bdqn.t350.dao.BaseDao;
import com.bdqn.t350.dao.PowerbatteryDao;
import com.bdqn.t350.entity.Powerbattery;
import com.bdqn.t350.service.PowerbatteryService;
import com.bdqn.t350.util.UploadAliYunUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PowerbatteryDaoImp extends BaseDao implements PowerbatteryDao {

    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;


    @Override
    public int add(Powerbattery powerbattery) {
        conn = this.getConnection();
        String sql = "INSERT INTO `powerbattery` (`carName`, `realFileName`, `saveFileName`, `suff`) " +
                "VALUES ( ?, ?, ?,?)";
        int count = 0;
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setObject(1, powerbattery.getCarName());
            pstmt.setObject(2, powerbattery.getRealFileName());
            pstmt.setObject(3, powerbattery.getSaveFileName());
            pstmt.setObject(4, powerbattery.getSuff());
            count = pstmt.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeAll(conn, pstmt, rs);
        }
        return count;
    }

    @Override
    public List<Powerbattery> list() {
        conn = this.getConnection();
        String sql = "SELECT id,carName,realFileName,saveFileName FROM `powerbattery` order by opsTime";
        Powerbattery powerbattery;
        List<Powerbattery> list = new ArrayList<>();
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                powerbattery = new Powerbattery();
                powerbattery.setId(rs.getInt("id"));
                powerbattery.setCarName(rs.getString("carName"));
                powerbattery.setSaveFileName(UploadAliYunUtil.ALI_DOMAIN + rs.getString("saveFileName"));
                powerbattery.setRealFileName(rs.getString("realFileName"));
                list.add(powerbattery);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeAll(conn, pstmt, rs);
        }

        return list;
    }
}
